package dfcf

import (
	"encoding/json"
	"fmt"
	"gitee.com/quant1x/data/category"
	"gitee.com/quant1x/data/category/trading"
	"github.com/mymmsc/gox/api"
	"github.com/mymmsc/gox/fastjson"
	"github.com/mymmsc/gox/http"
	"github.com/mymmsc/gox/logger"
	urlpkg "net/url"
)

const (
	kUrlEastmoneyGdfxHoldingAnalyse     = "https://datacenter-web.eastmoney.com/api/data/v1/get"
	EastmoneyGdfxHoldingAnalysePageSize = 500
)

type HoldingAnalyse struct {
	SECUCODE           string  `json:"SECUCODE"`           // "股票代码",
	SECURITY_NAME      string  `json:"SECURITY_NAME_ABBR"` // "股票简称",
	END_DATE           string  `json:"END_DATE"`           // "报告期",
	HOLDER_TYPE        string  `json:"HOLDER_TYPE"`        // "股东类型",
	HOLDER_NAME        string  `json:"HOLDER_NAME"`        // "股东名称",
	HOLD_NUM           int     `json:"HOLD_NUM"`           // "期末持股-数量",
	FREE_HOLDNUM_RATIO float64 `json:"FREE_HOLDNUM_RATIO"` // "-",
	HOLD_NUM_CHANGE    string  `json:"HOLD_NUM_CHANGE"`    // "期末持股-持股变动",
	CHANGE_RATIO       float64 `json:"CHANGE_RATIO"`       // "-",
	HOLDER_STATE       string  `json:"HOLDER_STATE"`       // "-",
	UPDATE_DATE        string  `json:"UPDATE_DATE"`        // "公告日",
	//HOLDER_MARKET_CAP  float64 `json:"HOLDER_MARKET_CAP"`  // "期末持股-流通市值",
	//HOLD_RATIO         float64 `json:"HOLD_RATIO"`         // "-",
	//SECURITY_CODE      string  `json:"SECURITY_CODE"`      // "股票代码简写",
	//HOLD_CHANGE        string  `json:"HOLD_CHANGE"`        // "-",
	//HOLD_RATIO_CHANGE  float64 `json:"HOLD_RATIO_CHANGE"`  // "期末持股-数量变化比例",
	//ORG_CODE                string  `json:"ORG_CODE"`                // "-",
	//IS_HOLDORG              string  `json:"IS_HOLDORG"`              // "-",
	//HOLDER_RANK             int     `json:"HOLDER_RANK"`             // "-",
	//HOLDER_CODE             string  `json:"HOLDER_CODE"`             // "-",
	//SECURITY_TYPE_CODE      string  `json:"SECURITY_TYPE_CODE"`      // "-",
	//SHARES_TYPE             string  `json:"SHARES_TYPE"`             // "-",
	//REPORT_DATE_NAME        string  `json:"REPORT_DATE_NAME"`        // "-",
	//HOLDER_NEW              string  `json:"HOLDER_NEW"`              // "-",
	//FREE_RATIO_QOQ          string  `json:"FREE_RATIO_QOQ"`          // "-",
	//HOLDER_STATEE           string  `json:"HOLDER_STATEE"`           // "-",
	//IS_REPORT               string  `json:"IS_REPORT"`               // "-",
	//HOLDER_CODE_OLD         string  `json:"HOLDER_CODE_OLD"`         // "-",
	//HOLDER_NEWTYPE          string  `json:"HOLDER_NEWTYPE"`          // "-",
	//HOLDNUM_CHANGE_NAME     string  `json:"HOLDNUM_CHANGE_NAME"`     // "-",
	//IS_MAX_REPORT_DATE      string  `json:"IS_MAX_REPORTDATE"`       // "-",
	//COOPERATION_HOLDER_MARK string  `json:"COOPERATION_HOLDER_MARK"` // "-",
	//MXID                    string  `json:"MXID"`                    // "-",
	//LISTING_STATE           string  `json:"LISTING_STATE"`           // "-",
	//XZCHANGE int `json:"XZCHANGE"` // "期末持股-数量变化",
	//NEW_CHANGE_RATIO        string  `json:"NEW_CHANGE_RATIO"`        // "-",
}

//type HoldingAnalyseSlice []HoldingAnalyse
//
//func (a HoldingAnalyseSlice) Len() int {
//	return len(a)
//}
//
//func (a HoldingAnalyseSlice) Swap(i, j int) {
//	a[i], a[j] = a[j], a[i]
//}
//
//// Less 重写Less()方法, 从大到小排序
//func (a HoldingAnalyseSlice) Less(i, j int) bool {
//	c1 := a[i].SECUCODE == a[j].SECUCODE
//	c2 := a[i].END_DATE > a[j].END_DATE
//	return c1 && c2
//}

// FreeHoldingAnalyse 东方财富网-数据中心-股东分析-股东持股明细-十大流通股东
//
//	https://data.eastmoney.com/gdfx/HoldingAnalyse.html
func FreeHoldingAnalyse(pageNumber ...int) ([]HoldingAnalyse, int, error) {
	pageNo := 1
	pages := 0
	if len(pageNumber) > 0 {
		pageNo = pageNumber[0]
	}
	pageSize := EastmoneyGdfxHoldingAnalysePageSize
	_, qEnd := category.GetQuarterDay(9)
	endDate := trading.FixTradeDate(qEnd)
	params := urlpkg.Values{
		"sortColumns": {"UPDATE_DATE,SECURITY_CODE,HOLDER_RANK"},
		"sortTypes":   {"-1,1,1"},
		"pageSize":    {fmt.Sprintf("%d", pageSize)},
		"pageNumber":  {fmt.Sprintf("%d", pageNo)},
		"reportName":  {"RPT_F10_EH_FREEHOLDERS"},
		"columns":     {"ALL"},
		"source":      {"WEB"},
		"client":      {"WEB"},
		"filter":      {fmt.Sprintf("(END_DATE>='%s')", endDate)},
	}
	url := kUrlEastmoneyGdfxHoldingAnalyse + "?" + params.Encode()
	data, err := http.HttpGet(url)
	var holds = []HoldingAnalyse{}
	obj, err := fastjson.ParseBytes(data)
	if err != nil {
		logger.Errorf("%+v\n", err)
		return holds, pages, err
	}
	result := obj.Get("result")
	if result == nil {
		return holds, pages, nil
	}
	pages = result.GetInt("pages")
	tData := result.Get("data")
	if tData == nil {
		return holds, pages, nil
	}
	text := tData.String()
	err = json.Unmarshal(api.String2Bytes(text), &holds)
	for i := 0; i < len(holds); i++ {
		holds[i].END_DATE = trading.FixTradeDate(holds[i].END_DATE)
		holds[i].UPDATE_DATE = trading.FixTradeDate(holds[i].UPDATE_DATE)
	}
	return holds, pages, err
}

// FreeHoldingDetail 拉取近期的
func FreeHoldingDetail() []HoldingAnalyse {
	pageNo := 1
	holds := []HoldingAnalyse{}
	for {
		list, pages, err := FreeHoldingAnalyse(pageNo)
		if err != nil || pages < 1 {
			logger.Error(err)
			break
		}
		count := len(list)
		if count == 0 {
			break
		}
		holds = append(holds, list...)
		if count < EastmoneyGdfxHoldingAnalysePageSize {
			break
		}
		pageNo += 1
	}
	return holds
}
